/**
 * 羊了个羊游戏主类
 */
class SheepGame {
  constructor() {
    // 游戏配置
    this.config = {
      maxSlots: 7,
      cardSize: { width: 50, height: 70 },
      padding: 15,
      layerHeight: 20,
      props: { remove: 1, undo: 1, shuffle: 1 }
    };

    // 游戏状态
    this.state = {
      currentLevel: 1,
      unlockedLevels: 1,
      slots: [],
      isGameOver: false,
      history: []
    };

    // 关卡配置
    this.levels = [
      {
        id: 1,
        name: "教学关",
        cardTypes: ['🐑', '🐶', '🐱'],
        cardCount: 9,
        difficulty: "简单",
        layers: 1,
        unlocked: true
      },
      {
        id: 2, 
        name: "进阶关",
        cardTypes: ['🐑', '🐶', '🐱', '🐭', '🐹'],
        cardCount: 15,
        difficulty: "普通",
        layers: 2,
        unlocked: false
      },
      {
        id: 3,
        name: "挑战关",
        cardTypes: ['🐑', '🐶', '🐱', '🐭', '🐹', '🐰', '🦊'],
        cardCount: 21,
        difficulty: "困难",
        layers: 3,
        unlocked: false
      }
    ];

    // 初始化游戏
    this.initDOM();
    this.initEvents();
    this.showScreen('level');
  }

  /**
   * 初始化DOM元素
   */
  initDOM() {
    this.dom = {
      levelScreen: document.getElementById('levelSelect'),
      gameScreen: document.getElementById('gameContainer'),
      resultScreen: document.getElementById('resultScreen'),
      gameBoard: document.getElementById('gameBoard'),
      slotsArea: document.querySelector('.slots'),
      levelInfo: document.querySelector('.level-info'),
      resultTitle: document.querySelector('.result-title'),
      resultMessage: document.querySelector('.result-message'),
      levelButtons: document.querySelectorAll('.level-btn'),
      backBtn: document.querySelector('.back-btn'),
      retryBtn: document.querySelector('.retry-btn'),
      nextBtn: document.querySelector('.next-btn'),
      backToLevelsBtn: document.querySelector('.back-to-levels')
    };
  }

  /**
   * 初始化事件监听
   */
  initEvents() {
    // 关卡选择事件
    this.dom.levelButtons.forEach(btn => {
      btn.addEventListener('click', () => {
        const levelId = parseInt(btn.dataset.level);
        if (this.isLevelUnlocked(levelId)) {
          this.startLevel(levelId);
        }
      });
    });

    // 游戏控制事件
    this.dom.backBtn.addEventListener('click', () => this.showScreen('level'));
    this.dom.retryBtn.addEventListener('click', () => this.retryLevel());
    this.dom.nextBtn.addEventListener('click', () => this.nextLevel());
    this.dom.backToLevelsBtn.addEventListener('click', () => this.showScreen('level'));
  }

  /**
   * 开始游戏关卡
   * @param {number} levelId 关卡ID
   */
  startLevel(levelId) {
    this.state.currentLevel = levelId;
    this.resetGameState();
    this.generateCards();
    this.initProps();
    this.showScreen('game');
  }

  /**
   * 重置游戏状态
   */
  resetGameState() {
    this.state.slots = [];
    this.state.isGameOver = false;
    this.state.history = [];
    this.state.props = { ...this.config.props };
    this.dom.gameBoard.innerHTML = '';
    this.dom.slotsArea.innerHTML = '';
    this.updateSlotDisplay();
  }

  /**
   * 生成游戏卡牌
   */
  generateCards() {
    const level = this.getCurrentLevel();
    const cards = [];
    
    // 创建卡牌数组（每种类型3张）
    level.cardTypes.slice(0, Math.ceil(level.cardCount / 3)).forEach(type => {
      cards.push(type, type, type);
    });

    // 洗牌
    this.shuffleArray(cards);

    // 创建DOM元素并定位
    cards.forEach((type, index) => {
      const card = document.createElement('div');
      card.className = 'card';
      card.textContent = type;
      card.dataset.type = type;
      
      // 计算位置（多层堆叠效果）
      const layer = index % level.layers;
      const left = this.config.padding + Math.random() * 
                   (this.dom.gameBoard.offsetWidth - this.config.cardSize.width - this.config.padding * 2);
      const top = this.config.padding + (layer * this.config.layerHeight);
      
      card.style.left = `${left}px`;
      card.style.top = `${top}px`;
      card.style.zIndex = layer + 1;
      
      card.addEventListener('click', () => this.handleCardClick(card));
      this.dom.gameBoard.appendChild(card);
    });
  }

  /**
   * 处理卡牌点击事件
   * @param {HTMLElement} card 被点击的卡牌元素
   */
  handleCardClick(card) {
    if (this.state.isGameOver) return;
    
    // 检查槽位是否已满
    if (this.state.slots.length >= this.config.maxSlots) {
      this.gameOver(false);
      return;
    }
    
    // 记录历史状态
    this.recordHistory();
    
    // 播放移动动画
    this.animateCardMove(card, () => {
      // 移动到槽位
      this.state.slots.push(card.dataset.type);
      card.remove();
      this.updateSlotDisplay();
      
      // 检查匹配
      this.checkMatches();
    });
  }

  /**
   * 检查卡牌匹配
   */
  checkMatches() {
    if (this.state.slots.length >= 3) {
      const lastThree = this.state.slots.slice(-3);
      if (new Set(lastThree).size === 1) {
        // 播放匹配动画
        this.animateCardMatch(() => {
          // 移除匹配的卡牌
          this.state.slots = this.state.slots.slice(0, -3);
          this.updateSlotDisplay();
          
          // 检查胜利条件
          if (this.dom.gameBoard.children.length === 0 && this.state.slots.length === 0) {
            this.gameOver(true);
          }
        });
      }
    }
  }

  /**
   * 游戏结束处理
   * @param {boolean} isWin 是否胜利
   */
  gameOver(isWin) {
    this.state.isGameOver = true;
    
    if (isWin) {
      // 解锁下一关
      if (this.state.currentLevel < this.levels.length) {
        this.levels[this.state.currentLevel].unlocked = true;
        this.state.unlockedLevels = Math.max(this.state.unlockedLevels, this.state.currentLevel + 1);
      }
    }
    
    this.showResult(isWin);
  }

  /**
   * 显示指定界面
   * @param {string} screen 界面类型 (level/game/result)
   */
  showScreen(screen) {
    this.dom.levelScreen.classList.toggle('hidden', screen !== 'level');
    this.dom.gameScreen.classList.toggle('hidden', screen !== 'game');
    this.dom.resultScreen.classList.toggle('hidden', screen !== 'result');
    
    if (screen === 'level') {
      this.updateLevelButtons();
    }
  }

  /**
   * 显示结果界面
   * @param {boolean} isWin 是否胜利
   */
  showResult(isWin) {
    this.dom.resultTitle.textContent = isWin ? '恭喜过关！' : '游戏结束';
    this.dom.resultMessage.textContent = isWin 
      ? `成功通过第${this.state.currentLevel}关`
      : '槽位已满，挑战失败';
    
    // 显示下一关按钮（如果不是最后一关）
    this.dom.nextBtn.classList.toggle('hidden', !isWin || this.state.currentLevel >= this.levels.length);
    
    this.showScreen('result');
  }

  /**
   * 初始化道具系统
   */
  initProps() {
    const propContainer = document.querySelector('.prop-container') || 
                         document.createElement('div');
    propContainer.className = 'prop-container';
    propContainer.innerHTML = '';
    
    // 创建三种道具按钮
    const props = [
      { name: 'remove', text: '移出' },
      { name: 'undo', text: '撤回' },
      { name: 'shuffle', text: '随机' }
    ];
    
    props.forEach(prop => {
      const btn = document.createElement('button');
      btn.className = 'prop-btn';
      btn.textContent = `${prop.text} (${this.state.props[prop.name]})`;
      btn.onclick = () => this.useProp(prop.name);
      propContainer.appendChild(btn);
    });
    
    document.querySelector('.game-header').after(propContainer);
  }

  /**
   * 使用道具
   * @param {string} type 道具类型
   */
  useProp(type) {
    if (this.state.props[type] <= 0) return;
    
    switch(type) {
      case 'remove':
        // 移出前3张卡牌
        if (this.state.slots.length >= 3) {
          this.state.slots = this.state.slots.slice(3);
        }
        break;
        
      case 'undo':
        // 撤回上一步操作
        if (this.state.history.length > 0) {
          const lastState = this.state.history.pop();
          this.state.slots = lastState.slots;
          
          // 重新生成游戏板
          this.dom.gameBoard.innerHTML = '';
          lastState.board.forEach((type, index) => {
            const card = document.createElement('div');
            card.className = 'card';
            card.textContent = type;
            card.dataset.type = type;
            card.style.zIndex = index;
            card.onclick = () => this.handleCardClick(card);
            this.dom.gameBoard.appendChild(card);
          });
        }
        break;
        
      case 'shuffle':
        // 随机移除一张卡牌
        if (this.state.slots.length > 0) {
          const randomIndex = Math.floor(Math.random() * this.state.slots.length);
          this.state.slots.splice(randomIndex, 1);
        }
        break;
    }
    
    this.state.props[type]--;
    this.updateSlotDisplay();
    this.updatePropButtons();
  }

  /**
   * 重试当前关卡
   */
  retryLevel() {
    this.startLevel(this.state.currentLevel);
  }

  /**
   * 进入下一关
   */
  nextLevel() {
    this.startLevel(this.state.currentLevel + 1);
  }

  /**
   * 记录游戏历史状态
   */
  recordHistory() {
    this.state.history.push({
      slots: [...this.state.slots],
      board: [...this.dom.gameBoard.children].map(c => c.dataset.type)
    });
  }

  /**
   * 更新槽位显示
   */
  updateSlotDisplay() {
    this.dom.slotsArea.innerHTML = '';
    this.state.slots.forEach(type => {
      const slot = document.createElement('div');
      slot.className = 'slot';
      slot.textContent = type;
      this.dom.slotsArea.appendChild(slot);
    });
    
    document.querySelector('.slot-title').textContent = 
      `槽位区 (${this.state.slots.length}/${this.config.maxSlots})`;
  }

  /**
   * 更新道具按钮状态
   */
  updatePropButtons() {
    const buttons = document.querySelectorAll('.prop-btn');
    buttons[0].textContent = `移出 (${this.state.props.remove})`;
    buttons[1].textContent = `撤回 (${this.state.props.undo})`;
    buttons[2].textContent = `随机 (${this.state.props.shuffle})`;
  }

  /**
   * 更新关卡按钮状态
   */
  updateLevelButtons() {
    this.dom.levelButtons.forEach(btn => {
      const levelId = parseInt(btn.dataset.level);
      const level = this.levels.find(l => l.id === levelId);
      btn.disabled = !level.unlocked;
      btn.innerHTML = level.unlocked 
        ? `第${levelId}关<br><small>${level.difficulty}</small>`
        : `第${levelId}关<br><small>已锁定</small>`;
    });
  }

  /**
   * 播放卡牌移动动画
   * @param {HTMLElement} card 卡牌元素
   * @param {Function} callback 动画完成回调
   */
  animateCardMove(card, callback) {
    card.style.zIndex = 1000;
    card.style.transition = 'transform 0.3s ease';
    card.style.transform = 'translateY(20px)';
    
    setTimeout(() => {
      callback();
      card.style.transition = '';
    }, 300);
  }

  /**
   * 播放卡牌匹配动画
   * @param {Function} callback 动画完成回调
   */
  animateCardMatch(callback) {
    const slots = document.querySelectorAll('.slot');
    const lastThree = Array.from(slots).slice(-3);
    
    lastThree.forEach(slot => {
      slot.classList.add('matched');
    });
    
    setTimeout(() => {
      lastThree.forEach(slot => {
        slot.classList.remove('matched');
      });
      callback();
    }, 500);
  }

  /**
   * 检查关卡是否解锁
   * @param {number} levelId 关卡ID
   * @returns {boolean}
   */
  isLevelUnlocked(levelId) {
    const level = this.levels.find(l => l.id === levelId);
    return level ? level.unlocked : false;
  }

  /**
   * 获取当前关卡数据
   * @returns {Object}
   */
  getCurrentLevel() {
    return this.levels.find(l => l.id === this.state.currentLevel) || this.levels[0];
  }

  /**
   * 洗牌算法
   * @param {Array} array 要洗牌的数组
   * @returns {Array}
   */
  shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
  }
}

// 启动游戏
document.addEventListener('DOMContentLoaded', () => {
  const game = new SheepGame();
  window.game = game; // 暴露到全局便于调试
});